<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/Breadcrumb' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item >权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮区 -->
            <el-row>
                <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
            </el-row>

            <!-- 角色列表区域 -->
            <el-table :data="rolelist" border stripe>
                <!-- 展开列 -->
                <el-table-column type=expand>
                    <template slot-scope="scope">
                        <el-row :class="['vcenter','bdtottom', i1 === 0 ? 'bdtop':'']"  v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级 权限-->
                            <el-col :span='19'>
                                <!-- 通过for循环 嵌套渲染二级权限 -->
                                <el-row :class="['vcenter',i2 ===0 ?'':'bdtop']" v-for= '(item2,i2) in item1.children' :key='item2.id'>
                                    <el-col :span="6">  
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag 
                                        type="warning"
                                         v-for= '(item3) in item2.children' :key='item3.id'
                                          closable @close="removeRightById(scope.row, item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row> 
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type='index'></el-table-column>
                <el-table-column label="角色名称" prop='roleName'></el-table-column>
                <el-table-column label="角色描述" prop='roleDesc'></el-table-column>
                <el-table-column label="操作" width="285px">
                    <template slot-scope="scope">
                        <el-button size='mini' type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
                        <el-button size='mini' type="danger" icon="el-icon-edit"  @click="removeRoleById(scope.row.id)">删除</el-button>
                        <el-button size='mini' type="warning" icon="el-icon-edit" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 添加角色的对话框 -->
            <el-dialog
                title="添加角色"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addDialogClosed()">
                <!-- 内容主体区域 -->
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                    <el-form-item label="角色名称" prop="roleName" label-width="80px">
                        <el-input v-model="addForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述"  prop="roleDesc">
                        <el-input v-model="addForm.roleDesc" ></el-input>
                    </el-form-item>
                </el-form>
                <!-- 底部区 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addRole()">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 修改角色的对话框 -->
            <el-dialog
                    title="修改角色"
                    :visible.sync="editDialogVisible"
                    width="50%"
                    @close="addDialogClosed()">
                    <!-- 内容主体区域 -->
                    <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
                        <el-form-item label="角色名称" prop="roleName" label-width="80px">
                            <el-input v-model="editForm.roleName"></el-input>
                        </el-form-item>
                        <el-form-item label="角色描述"  prop="roleDesc">
                            <el-input v-model="editForm.roleDesc" ></el-input>
                        </el-form-item>
                    </el-form>
                    <!-- 底部区 -->
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="addDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="editRole()">确 定</el-button>
                    </span>
                </el-dialog>
        
            <!-- 分配权限 -->
            <el-dialog title="分配权限列表" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
            <el-tree :data="rigthsList" :props="treeProps" :highlight-current="true" :default-checked-keys="defaultCheckedId"
                ref="treeRef" show-checkbox node-key="id" :check-on-click-node="true" :default-expand-all="true"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allRights">确 定</el-button>
            </span>
            </el-dialog>


        </el-card>
    </div>
</template>
<script>
export default {
    data() {
        return {      
            setRightDialogVisible: false,
            rigthsList: [],
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            defaultCheckedId: [],
            //即将分配权限的角色id
            roleId: '',
            //所有角色列表数据
            rolelist:[],
            //控制添加角色对话框的显示和隐藏
            addDialogVisible:false,
            //添加角色的表单数据
            addForm:{
                roleId:'',
                roleName:'',
                roleDesc:'',
            },
            //添加用户表单的验证规则对象
            addFormRules:{
                //验证用户名是否合法
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    {
                        min: 2,
                        max: 10,
                        message: '长度在 2 到 10 个字符',
                        trigger: 'blur',
                    },
                ],
                roleDesc:[
                    { required: false, message: '请输入角色描述', trigger: 'blur' },
                    {
                        min: 0,
                        max: 30,
                        message: '长度在 0 到 30 个字符',
                        trigger: 'blur',
                    },
                ],
            },
            //控制修改对话框的显示与隐藏
            editDialogVisible:false,
            //修改对话框数据对象
            editForm:{
                roleId:'',
                roleName:'',
                roleDesc:'',
            },
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        //获取所有角色的列表
        async getRolesList(){
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status !==200 ){
                return this.$message.error('获取角色列表失败!')
            }
            this.rolelist = res.data

        },
        //点击确定按钮，添加新角色
        addRole(){
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return
                //可以发起添加角色的网络请求
                const {data:res} = await this.$http.post('roles',this.addForm)
                if(res.meta.status !== 201){
                    this.$message.error('添加用户失败！')
                }else{
                    this.$message.success('添加用户成功！')
                    //隐藏添加角色的对话框
                    this.addDialogVisible = false
                    //重新获取角色列表数据
                    this.getRolesList()
                }
            })
        },
        //监听添加角色对话框的关闭事件
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        async showEditDialog(id){
            console.log(id)
            this.editDialogVisible = true
            const {data:res} = await this.$http.get('roles/'+id)
            this.editForm = res.data
                  
        },
        async addRole(){
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return this.$message.error("错了哦,请输入有效的信息");
                const { data: res } = await this.$http.post('roles',this.addForm)
                if (res.meta.status != 201) {
                    this.$message.error('添加角色' + res.meta.msg + "失败!!!");
                };
                this.addDialogVisible = false
                this.$message.success('添加角色' + res.meta.msg+"成功！")
                this.getRolesList()
            })
        },
        async removeRightById(role, rightId) {
            const confirmResult = await this.$confirm('此操作将永久删除角色权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch((error) => {
            })
            if (confirmResult != 'confirm') {
                return this.$message({
                type: 'info',
                message: '已取消删除'
                });
            } else {
                const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if (res.meta.status != 200) return this.$message.error(res.meta.msg)
                this.$message.success(res.meta.msg)
                role.children = res.data
                // this.getRolesList()
            }
        },
        async showSetRightDialog(role) {
            this.setRightDialogVisible = true
            this.roleId = role.id
            const { data: res } = await this.$http.get('/rights/tree')
            if (res.meta.status != 200) return this.$message.error(res.meta.msg)
            console.log("后端返回的数据："+res.data)
            this.rigthsList = res.data
            this.getDeafkeys(role, this.defaultCheckedId)            
            
            
        },
        // 根据递归，获取角色下所有三级权限的id，并保存到defaultCheckedId的数组中
        getDeafkeys(node, arr) {
        if (!node.children) {
            return arr.push(node.id)
        } else {
            node.children.forEach(item => {
            this.getDeafkeys(item, arr)
            });
        }
        },
        async allRights() {
        // 得到角色权限的id
        // getCheckedKeys(),getHalfCheckedKeys()方法可以获取节点数据
        const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
        const idStr = keys.join(',')

        // 在showSetRightDialog事件里保存了roleId
        const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`
        ,{rids:idStr})
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        this.rigthsList = res.data
        this.$message.success('权限列表' + res.meta.msg)
        this.getRolesList()
        this.setRightDialogVisible = false
        },
        //监听分配权限对话框的关闭事件
        setRightDialogClosed(){
            this.defaultCheckedId = []
        },
        async removeRoleById(id) {
            const confirmResult = await this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch((error) => {
            })
            if (confirmResult != 'confirm') {
                return this.$message({
                type: 'info',
                message: '已取消删除'
                });
            } else {
                const { data: res } = await this.$http.delete(`roles/${id}`)
                if (res.meta.status != 200) return this.$message.error(res.meta.msg)
                console.log(res.data)
                this.$message.success(res.meta.msg)
                this.getRolesList()

            }
        },
        async editRole(){
            this.$refs.editFormRef.validate(async valid => {
                const id = this.editForm.roleId
                if (!valid) return this.$message.error("错了哦,请输入有效的信息");
                const { data: res } = await this.$http.put(`roles/${id}`,this.editForm)
                if (res.meta.status != 201) {
                    this.$message.error('修改角色失败!!!');
                };
                this.$message.success('修改角色 成功！')
                this.getRolesList()
                this.editDialogVisible = false
            })
        },

    },
}
</script>
<style lang="less" scoped>
.vcenter{
    display: flex;
    align-items: center;
}
</style>